package ay.shadow.order.service.impl;

import ay.shadow.core.utils.SnowflakeIdGenerator;
import ay.shadow.order.entity.Order;
import ay.shadow.order.mapper.OrderMapper;
import ay.shadow.order.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Resource
    private OrderMapper orderMapper;
    private SnowflakeIdGenerator idGenerator;

    // 初始化雪花算法生成器（工作节点ID和数据中心ID可配置）
    @PostConstruct
    public void init() {
        this.idGenerator = new SnowflakeIdGenerator(1, 1);
    }

    /**
     * 创建订单
     */
    @Override
    public int createOrder(Order order) {
        // 生成唯一订单号
        order.setOrderNo(String.valueOf(idGenerator.nextId()));
        // 插入订单（ShardingSphere自动路由到对应分表）
        return orderMapper.insertVo(order);
    }

    /**
     * 根据用户ID查询订单
     */
    @Override
    public List<Order> getOrdersByUserId(Long userId) {
        return orderMapper.selectByUserId(userId);
    }

    /**
     * 根据订单号查询订单
     */
    @Override
    public Order getOrderByNo(String orderNo) {
        return orderMapper.selectByOrderNo(orderNo);
    }
}
